package com.punai.config.sqlitedao.impl;


import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.punai.common.exception.ServiceException;
import com.punai.common.utils.sqlite.SqliteUtil;
import com.punai.config.constants.PnConfigConstants;
import com.punai.config.sqlitedao.StructureLinkItemRepository;
import com.punai.config.sqlitedomain.StructureLinkItem;
import com.punai.config.sqlitesetting.SqliteSystemTemplConnection;
import io.netty.util.internal.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Component
public class StructureLinkItemRepositoryImpl implements StructureLinkItemRepository {
    private static SqliteUtil sqliteUtil;
    private static final Logger log = LoggerFactory.getLogger(StructureLinkItemRepository.class);

    @Autowired
    private SqliteSystemTemplConnection sqliteSystemTemplConnection;

    private void initConnection() {
        sqliteUtil = sqliteSystemTemplConnection.initConnection();
    }
    @Override
    public List<StructureLinkItem> findByStrutsIdAndItemPid(String strutsId, String itemPid)  {
        if(StringUtil.isNullOrEmpty(strutsId)) throw new ServiceException("查找指标表与指标项关系失败：指标表Id不能为空");
        initConnection();
        String sql="select " +
                "* " +
                "from " +
                "tab_config_link_struts_item " +
                "where " +
                "STRUTS_ID = '"+strutsId+"' ";
        if(StrUtil.isNotBlank(itemPid)) sql+=" and ELEMENT_PID = '"+itemPid+"'";
        if (StringUtil.isNullOrEmpty(itemPid)) sql += "and ELEMENT_PID is null";
        String order=" order by sorting";
        sql +=order;
        return sqliteUtil.selectListRecord(StructureLinkItem.class,sql);
    }

    @Override
    public List<StructureLinkItem> findByStrutsId(String strutsId)  {
        if (StringUtil.isNullOrEmpty(strutsId)) throw new ServiceException("查找指标表与指标项关系失败：指标表Id不能为空");
        initConnection();
        String sql = "select " +
                "* " +
                "from " +
                "tab_config_link_struts_item " +
                "where " +
                "STRUTS_ID = '" + strutsId + "' ";
        String order = " order by sorting";
        sql += order;
        return sqliteUtil.selectListRecord(StructureLinkItem.class, sql);
    }

    @Override
    public List<StructureLinkItem> findByStrutsId(Set<String> strutsIds)  {
        initConnection();
        String sql = "select " +
                "* " +
                "from " +
                "tab_config_link_struts_item " +
                "where " +
                "STRUTS_ID in ('" + StrUtil.join(",",strutsIds) + "') ";
        String order = " order by sorting";
        sql += order;
        return sqliteUtil.selectListRecord(StructureLinkItem.class, sql);
    }

    @Override
    public StructureLinkItem findOne(String oid) {
        initConnection();

        String sql = "select * from tab_config_link_struts_item where " +
                "ID = '" + oid + "'";
        return sqliteUtil.selectOneRecord(StructureLinkItem.class, sql);
    }
    @Override
    public StructureLinkItem delete(String oid) {
        initConnection();

        String sql = "select * from tab_config_link_struts_item where " +
                "ID = '" + oid + "'";
        StructureLinkItem one = sqliteUtil.selectOneRecord(StructureLinkItem.class, sql);
        sql = "delete from tab_config_link_struts_item where " +
                "ID = '" + oid + "'";
        sqliteUtil.execute(sql);
        return one;
    }

    @Override
    public void delete(Set<String> deleteIds) {
        String sql = "delete from tab_config_link_struts_item where " +
                "ID in('"+StrUtil.join(",",deleteIds)+"')";
        sqliteUtil.execute(sql);
    }

    @Override
    public StructureLinkItem findByStrutsIdAndItemId(String strutsId, String oid)  {
        if (StringUtil.isNullOrEmpty(strutsId)) throw new ServiceException("查找指标表与指标项关系失败：指标表Id不能为空");
        initConnection();
        String sql = "select " +
                "* " +
                "from " +
                "tab_config_link_struts_item " +
                "where " +
                "STRUTS_ID = '" + strutsId + "' "+
                " and ELEMENT_ID = '" + oid + "'";
        return sqliteUtil.selectOneRecord(StructureLinkItem.class, sql);
    }

    @Override
    public void updateCalculationCodeAndIsHz(StructureLinkItem one)  {
        initConnection();
        String sql="update tab_config_link_struts_item set CALCULATION_CODE =?,IS_HZ=? where ID=?";
        Object[] args = new Object[]{
                one.getCalculationCode(),
                one.getIsHz(),
                one.getId(),
        };
        int rownumber = sqliteUtil.execute(sql, args);
        if (rownumber == 0) {
            throw new ServiceException("sqlite.message.updateException");
        }
    }

    @Override
    public Integer findMaxSorting() {
        initConnection();
        String sql = "select max(sorting) as sorting from tab_config_link_struts_item";
        StructureLinkItem link = sqliteUtil.selectOneRecord(StructureLinkItem.class, sql);
        return link.getSorting();
    }

    @Override
    public StructureLinkItem save(StructureLinkItem structureLinkItem)  {
        initConnection();
        String Sql = "insert into "
                + "tab_config_link_struts_item" +
                "(ID ," +
                "ELEMENT_ID ," +
                "STRUTS_ID ," +
                "CREATE_DATE ," +
                "EDIT_STATE ," +
                "LAST_MODIFY ," +
                "SREACH_KEY ," +
                "VERSION ," +
                "PARENT_CODE ," +
                "SORTING ," +
                "CALCULATION_CODE ," +
                "ELEMENT_PID," +
                "IS_HZ ) "
                + "values(?,?,?,?,?,?,?,?,?,?,?,?,?) ";
        structureLinkItem.setEditState(PnConfigConstants.EDITSTATE.SAVESTATE.getType());
        structureLinkItem.setVersion(Integer.parseInt(String.valueOf(PnConfigConstants.ENTITY_VERSION)));
        structureLinkItem.setSreachKey(structureLinkItem.toString());
        structureLinkItem.setId(IdUtil.fastUUID());
        Object[] args = new Object[]{
                structureLinkItem.getId(),
                structureLinkItem.getElementId(),
                structureLinkItem.getStrutsId(),
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()),
                structureLinkItem.getEditState(),
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()),
                structureLinkItem.getSreachKey(),
                structureLinkItem.getVersion(),
                structureLinkItem.getParentCode(),
                structureLinkItem.getSorting(),
                structureLinkItem.getCalculationCode(),
                structureLinkItem.getElementPid(),
                structureLinkItem.getIsHz()

        };
        int rownumber = sqliteUtil.execute(Sql, args);
        if (rownumber == 0) {
            throw new ServiceException("sqlite.message.addException");
        }
        return structureLinkItem;
    }

    @Override
    public void deleteByStrutsIdAndItemIds(String strutsId, Set<String> deleteItemIds,String elePid) {
        initConnection();

        String sql="delete from tab_config_link_struts_item where " +
                "STRUTS_ID = '"+strutsId+"' ";
        if (deleteItemIds!=null&&deleteItemIds.size()>0){
            sql += "and ELEMENT_ID in ('" + StrUtil.join("','",deleteItemIds) + "') ";
        }
        if(StrUtil.isNotBlank(elePid)&&!elePid.equals("1008611")) sql+="and ELEMENT_PID = '"+elePid+"' ";
        if(StringUtil.isNullOrEmpty(elePid)) sql += "and ELEMENT_PID is null ";
        sqliteUtil.execute(sql);
    }

    @Override
    public List<StructureLinkItem> findItemsByStrutsId(String strutsId,String itemName)  {
        if (StringUtil.isNullOrEmpty(strutsId)) throw new ServiceException("查找指标表与指标项关系失败：指标表Id不能为空");
        initConnection();
        String select = "select  " +
                " * " +
                " from tab_config_indicator_item item  " +
                " left join tab_config_link_struts_item link on link.ELEMENT_ID = item.id " +
                " where link.struts_id = '"+strutsId+"' ";
        String where = "";
        if (StrUtil.isNotBlank(itemName)) {
            where = where + " and NAME LIKE '%" + itemName + "%' ";
        }
        String order = " order by sorting";
        String sql = select + where + order;
        return sqliteUtil.selectListRecord(StructureLinkItem.class, sql);
    }

    @Override
    public StructureLinkItem update(StructureLinkItem structureLinkItem)  {
        initConnection();
        String Sql = "update tab_config_link_struts_item set "+
                "ELEMENT_ID=?," +
                "STRUTS_ID=?," +
                "EDIT_STATE=?," +
                "SREACH_KEY=?," +
                "VERSION=?,"+
                "PARENT_CODE=?," +
                "SORTING=?," +
                "calculation_code=?," +
                "ELEMENT_PID=?," +
                "LAST_MODIFY=?  " +
                " where id = ?";
        structureLinkItem.setSreachKey(structureLinkItem.toString());
        Object[] args = new Object[]{
                structureLinkItem.getElementId(),
                structureLinkItem.getStrutsId(),
                structureLinkItem.getEditState(),
                structureLinkItem.getSreachKey(),
                structureLinkItem.getVersion(),
                structureLinkItem.getParentCode(),
                structureLinkItem.getSorting(),
                structureLinkItem.getCalculationCode(),
                structureLinkItem.getElementPid(),
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()),
                structureLinkItem.getId()
        };
        int rownumber = sqliteUtil.execute(Sql, args);
        if (rownumber == 0) {
            throw new ServiceException("sqlite.message.updateException");
        }
        return  structureLinkItem;
    }

    @Override
    public void updateSort(String id, Integer targetSorting) {
        initConnection();
        String sql = "update tab_config_link_struts_item set SORTING = " + targetSorting + " where id = '" + id + "'";
        int execute = sqliteUtil.execute(sql);
        if (execute == 0) {
            throw new ServiceException("sqlite.message.updateException");
        }
    }
}
